package _interview75;

/**
 * 72. 编辑距离
 */
public class No72 {
    private String word1, word2;
    private int[][] cache;

    public int minDistance(String word1, String word2) {
        this.word1 = word1;
        this.word2 = word2;
        int n = word1.length();
        int m = word2.length();
        cache = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cache[i][j] = -1;
            }
        }
        return dfs(n - 1, m - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0) return j + 1;
        else if (j < 0) return i + 1;
        else if (cache[i][j] != -1) return cache[i][j];
        else if (word1.charAt(i) == word2.charAt(j)) return cache[i][j] = dfs(i - 1, j - 1);
        else return cache[i][j] = Math.min(dfs(i - 1, j - 1), Math.min(dfs(i - 1, j), dfs(i, j - 1))) + 1;
    }
}
